﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml;
using RobotGerchik.DataClass;
using RobotGerchik.DataClass.BaseTransaqCalss;
using System.Linq;

namespace RobotGerchik
{
    public partial class MainWindow
    {
        public Securities SecuritiesItem;
        public ClientAccount ClientAccountItem;
        public Candles CandlesItem;
        public Quotations QuotationsItem;
        public AllTrades AllTradesItem;
        public Order OrderItem;
        public StopOrder StopOrderItem;
        public Deal DealItem;
        public MoneyPosition MoneyPositionItem;
        public SecPosition SecPositionItem;
        public Tick TickItem;

        public static Dictionary<int, string> DictionaryMarkets;
        public static Dictionary<int, string> DictionaryTimeFrame;
        string _level2; //для получения данных к узалам внутри узла второго уровня
        string _level1; //для получения данных к узалам внутри узла первого уровня


        public void Transaq_HandleData(string data)
        {



            // обработка данных, полученных коннектором от сервера Транзак
            string sTime = DateTime.Now.ToString("HH:mm:ss.fff");
            string info = "";
            _level2 = "";
            _level1 = "";
            // включить полученные данные в строку вывода в лог-файл
            string textForWindow = data;
            WriteLog("ServerData: " + data);


            XmlReaderSettings xs = new XmlReaderSettings();
            xs.IgnoreWhitespace = true;
            xs.ConformanceLevel = ConformanceLevel.Fragment;
            xs.ProhibitDtd = false;
            XmlReader xr = XmlReader.Create(new System.IO.StringReader(data), xs);
            string section = "";
            string line = "";
            string str = "";
            string ename = "";
            string evalue = "";
            string attr = "";
            //string values = "";

            // обработка "узлов" 
            while (xr.Read())
            {
                switch (xr.NodeType)
                {
                    case XmlNodeType.Element:
                    case XmlNodeType.EndElement:
                        ename = xr.Name; break;
                    case XmlNodeType.Text:
                    case XmlNodeType.CDATA:
                    case XmlNodeType.Comment:
                    case XmlNodeType.XmlDeclaration:
                        evalue = xr.Value; break;
                    case XmlNodeType.DocumentType:
                        ename = xr.Name; evalue = xr.Value; break;
                    default: break;
                }

                #region определяем узел верхнего уровня - "секцию"
                if (xr.Depth == 0)
                {
                    if (xr.NodeType == XmlNodeType.Element)
                    {
                        section = ename;

                        if ((section != "boards") && (section != "securities") && (section != "pits") && (section != "sec_info_upd") && (textForWindow.Length > 0))
                        {
                            lsbxAnswer.Items.Add(sTime + ": " + textForWindow + "\n =================================================== \n");
                            textForWindow = "";
                        }

                        line = "";
                        str = "";
                        for (int i = 0; i < xr.AttributeCount; i++)
                        {
                            str = str + xr.GetAttribute(i) + ";";
                        }
                    }
                    if (xr.NodeType == XmlNodeType.EndElement)
                    {
                        //line = "";
                        //section = "";
                    }
                    if (xr.NodeType == XmlNodeType.Text)
                    {
                        str = str + evalue + ";";
                    }
                }
                #endregion

                #region Рынки markets

                if (section == "markets")
                {
                    //xe = (XElement)XNode.ReadFrom(xr);

                    if (ename == "market")
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            line = "";
                            str = "";
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                str = str + xr.GetAttribute(i) + ";";
                            }
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                        {
                            if (!DictionaryMarkets.ContainsKey(Convert.ToInt32((str.Split(';'))[0])))
                                DictionaryMarkets.Add(Convert.ToInt32((str.Split(';'))[0]), (str.Split(';'))[1]);
                            line = "add market: " + str;

                            str = "";
                        }
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                            str = str + evalue + ";";
                        }
                    }
                }
                #endregion

                #region Данные по доступным таймфремам candlekinds

                if (section == "candlekinds")
                {
                    if (ename == "kind")
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            line = "";
                            str = "";
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                        {
                            if (!DictionaryTimeFrame.ContainsKey(Convert.ToInt32((str.Split(';'))[0])))
                                DictionaryTimeFrame.Add(Convert.ToInt32((str.Split(';'))[0]), (str.Split(';'))[2]);
                            line = "add kind: " + str;

                            //Add_Timeframe(str);
                            str = "";
                        }
                    }
                    else
                    {
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                            str = str + evalue + ";";
                        }
                    }
                }
                #endregion

                #region Данные по инструментам

                if (section == "securities")
                {
                    if (ename == "security")
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            SecuritiesItem = new Securities();
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                if (i == 0)
                                    SecuritiesItem.Secid = Convert.ToInt32(xr.GetAttribute(i));
                                if (i == 1)
                                    SecuritiesItem.Active = Convert.ToBoolean(xr.GetAttribute(i));
                            }
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                            AddSecurities();
                    }
                    else
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                str = str + xr.GetAttribute(i) + ";";
                            }
                        }
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                            if (ename == SecuritiesEnum.market.ToString())
                                SecuritiesItem.Market = Convert.ToInt32(evalue);
                            if (ename == SecuritiesEnum.seccode.ToString())
                                SecuritiesItem.Seccode = evalue;
                            if (ename == SecuritiesEnum.board.ToString())
                                SecuritiesItem.Board = evalue;
                            if (ename == SecuritiesEnum.shortname.ToString())
                                SecuritiesItem.Shortname = evalue;

                            if (ename == SecuritiesEnum.decimals.ToString())
                                SecuritiesItem.Decimals = Convert.ToInt32(evalue);
                            if (ename == SecuritiesEnum.minstep.ToString())
                                SecuritiesItem.Minstep = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == SecuritiesEnum.lotsize.ToString())
                                SecuritiesItem.Lotsize = Convert.ToInt32(evalue);
                            if (ename == SecuritiesEnum.pointCost.ToString())
                                SecuritiesItem.Point_cost = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == SecuritiesEnum.sectype.ToString())
                                SecuritiesItem.SecType = evalue;


                            str = str + evalue + ";";
                        }
                    }
                }
                #endregion

                #region Данные по клиенту client
                if (section == "client")
                {
                    if (ename == "client")
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            ClientAccountItem = new ClientAccount();

                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                if (i == 0)
                                    ClientAccountItem.ID = xr.GetAttribute(i);
                            }
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                            AddClientAccount();
                    }
                    else
                    {
                        line = "";
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                            if (ename == ClietnAccountEnum.currency.ToString())
                                ClientAccountItem.Currency = evalue;
                            if (ename == ClietnAccountEnum.type.ToString())
                                ClientAccountItem.Type = evalue;
                            if (ename == ClietnAccountEnum.ml_intraday.ToString())
                                ClientAccountItem.MlInterday = Convert.ToDouble(evalue);
                            if (ename == ClietnAccountEnum.ml_overnight.ToString())
                                ClientAccountItem.MlOverNight = Convert.ToDouble(evalue);
                            //str = str + evalue + ";";
                            //line = "set: " + ename + "=" + evalue;
                        }
                    }
                }
                #endregion

                #region Данные по позициям positions

                if (section == "positions")
                {
                    #region money_position

                    if (ename == "money_position")
                    {
                        if (xr.Depth == 1)
                            _level1 = ename;
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            MoneyPositionItem = new MoneyPosition();
                            MoneyPositionItem.Market = new List<int>();
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                        {
                            AddMoneyPosition();
                        }
                    }
                    if (_level1 == "money_position")
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                str = str + xr.GetAttribute(i) + ";";
                            }
                        }
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                            if (ename == MoneyPositionEnum.client.ToString())
                                MoneyPositionItem.Client = evalue;
                            if (ename == MoneyPositionEnum.market.ToString())
                                MoneyPositionItem.Market.Add(Convert.ToInt32(evalue));
                            if (ename == MoneyPositionEnum.register.ToString())
                                MoneyPositionItem.Register = evalue;
                            if (ename == MoneyPositionEnum.asset.ToString())
                                MoneyPositionItem.Asset = evalue;
                            if (ename == MoneyPositionEnum.shortname.ToString())
                                MoneyPositionItem.Shortname = evalue;

                            if (ename == MoneyPositionEnum.saldoin.ToString())
                                MoneyPositionItem.Saldoin = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == MoneyPositionEnum.bought.ToString())
                                MoneyPositionItem.Bought = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == MoneyPositionEnum.sold.ToString())
                                MoneyPositionItem.Sold = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == MoneyPositionEnum.saldo.ToString())
                                MoneyPositionItem.Saldo = Convert.ToDouble(evalue.Replace('.', ','));

                            if (ename == MoneyPositionEnum.ordbuy.ToString())
                                MoneyPositionItem.Ordbuy = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == MoneyPositionEnum.ordbuycond.ToString())
                                MoneyPositionItem.Ordbuycond = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == MoneyPositionEnum.comission.ToString())
                                MoneyPositionItem.Comission = Convert.ToDouble(evalue.Replace('.', ','));
                        }
                    }

                    #endregion

                    #region money_position

                    if (ename == "sec_position")
                    {
                        if (xr.Depth == 1)
                            _level1 = ename;
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            SecPositionItem = new SecPosition();
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                        {
                            AddSecPosition();
                        }
                    }
                    if (_level1 == "sec_position")
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                str = str + xr.GetAttribute(i) + ";";
                            }
                        }
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                            if (ename == SecPositionEnum.secid.ToString())
                                SecPositionItem.Secid = Convert.ToInt32(evalue);
                            if (ename == SecPositionEnum.market.ToString())
                                SecPositionItem.Market = Convert.ToInt32(evalue);
                            if (ename == SecPositionEnum.seccode.ToString())
                                SecPositionItem.Seccode = evalue;
                            if (ename == SecPositionEnum.register.ToString())
                                SecPositionItem.Register = evalue;
                            if (ename == SecPositionEnum.client.ToString())
                                SecPositionItem.Client = evalue;
                            if (ename == SecPositionEnum.shortname.ToString())
                                SecPositionItem.Shortname = evalue;

                            if (ename == SecPositionEnum.saldomin.ToString())
                                SecPositionItem.Saldomin = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == SecPositionEnum.saldoin.ToString())
                                SecPositionItem.Saldoin = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == SecPositionEnum.bought.ToString())
                                SecPositionItem.Bought = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == SecPositionEnum.sold.ToString())
                                SecPositionItem.Sold = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == SecPositionEnum.saldo.ToString())
                                SecPositionItem.Saldo = Convert.ToDouble(evalue.Replace('.', ','));

                            if (ename == SecPositionEnum.ordbuy.ToString())
                                SecPositionItem.Ordbuy = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == SecPositionEnum.ordsell.ToString())
                                SecPositionItem.Ordsell = Convert.ToDouble(evalue.Replace('.', ','));
                        }
                    }

                    #endregion
                }

                #endregion

                #region OverNight overnight
                if (section == "overnight")
                {
                    if (xr.NodeType == XmlNodeType.Element)
                    {
                        line = "";
                        str = "";
                        for (int i = 0; i < xr.AttributeCount; i++)
                        {
                            str = str + "<" + xr.GetAttribute(i) + ">;";
                        }
                        line = "set overnight status: " + str;
                    }
                }
                #endregion

                #region Данные о статусе соденинеия с сервером server_status
                if (section == "server_status")
                {
                    if (xr.NodeType == XmlNodeType.Element)
                    {
                        line = "";
                        str = "";
                        for (int i = 0; i < xr.AttributeCount; i++)
                        {
                            attr = xr.GetAttribute(i);
                            str = str + i.ToString() + ":<" + attr + ">;";
                            if (i == 1)
                            {
                                if (attr == "true")
                                {
                                    str = str + "attr:" + attr + ";";
                                    if (BConnecting && !BConnected)
                                    {
                                        ShowStatus("Подключение установлено");
                                        chbxConnectin.IsChecked = true;
                                    }
                                    BConnecting = false;
                                    BConnected = true;
                                }
                                if (attr == "false")
                                {
                                    str = str + "attr:" + attr + ";";
                                    if (BDisconnecting)
                                    {
                                        ClearCollection();
                                        ShowStatus("Подключение разъединено");
                                        chbxConnectin.IsChecked = false;
                                    }
                                    BDisconnecting = false;
                                    BConnected = false;
                                }
                                Transaq_Reflect();
                            }
                        }
                        line = "set server_status: " + str;
                    }
                    if (xr.NodeType == XmlNodeType.Text)
                    {
                        BConnecting = false;
                        Transaq_Reflect();
                        ShowStatus("Server status: " + evalue);
                    }
                }
                #endregion

                #region Данные по истории свечи candles

                if (section == "candles")
                {
                    if (ename == "candles")
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            bool addCandles = true;
                            CandlesItem = new Candles();
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                if (i == 0)
                                    CandlesItem.Secid = Convert.ToInt32(xr.GetAttribute(i));
                                if (i == 1)
                                    CandlesItem.Board = xr.GetAttribute(i);
                                if (i == 2)
                                    CandlesItem.Seccode = xr.GetAttribute(i);
                                if (i == 3)
                                    CandlesItem.Period = Convert.ToInt32(xr.GetAttribute(i));
                                if (i == 4)
                                {
                                    //CandlesItem.Status = Convert.ToInt32(xr.GetAttribute(i));
                                    if (!DataProvider.CandlesItems.Contains(CandlesItem))
                                    {
                                        CandlesItem.Candle = new ObservableCollection<Candle>();
                                        if (DataProvider.CandlesItems.Count > 0)
                                            DataProvider.CandlesItems.Remove(CandlesItem);
                                        for (int j = 0; j < DataProvider.CandlesItems.Count; j++)
                                        {

                                            if (DataProvider.CandlesItems[j].Board == CandlesItem.Board &&
                                                DataProvider.CandlesItems[j].Seccode == CandlesItem.Seccode &&
                                                DataProvider.CandlesItems[j].Period == CandlesItem.Period)
                                            {
                                                //DataProvider.CandlesItems[j].Candle.Clear();
                                                addCandles = false;
                                            }
                                        }
                                        //foreach (var itemCandle in DataProvider.CandlesItems)
                                        //{
                                        //    if (itemCandle.Board == CandlesItem.Board &&
                                        //        itemCandle.Seccode == CandlesItem.Seccode &&
                                        //        itemCandle.Period == CandlesItem.Period)

                                        //        itemCandle.
                                        //    {
                                        //        DataProvider.CandlesItems.Remove(itemCandle);
                                        //    }
                                        //}
                                        if (addCandles == true)
                                            DataProvider.CandlesItems.Add(CandlesItem);
                                    }
                                }

                            }
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                        {
                        }

                    }
                    else
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            bool addCandle = true;
                            Candle candle = new Candle();
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                var dfd = xr.GetAttribute(i);
                                if (i == 0)
                                    candle.DateTime = Convert.ToDateTime(xr.GetAttribute(i));
                                if (i == 1)
                                    candle.Open = Convert.ToDouble(xr.GetAttribute(i).Replace('.', ','));
                                if (i == 2)
                                    candle.Close = Convert.ToDouble(xr.GetAttribute(i).Replace('.', ','));
                                if (i == 3)
                                    candle.High = Convert.ToDouble(xr.GetAttribute(i).Replace('.', ','));
                                if (i == 4)
                                    candle.Low = Convert.ToDouble(xr.GetAttribute(i).Replace('.', ','));
                                if (i == 5)
                                    candle.Volume = Convert.ToInt32(xr.GetAttribute(i).Replace('.', ','));
                                if (i == 6)
                                {
                                    candle.Oi = Convert.ToInt32(xr.GetAttribute(i));

                                }
                                if (i == xr.AttributeCount - 1)
                                {
                                    foreach (var itemCandle in DataProvider.CandlesItems)
                                    {
                                        if (itemCandle.Board == CandlesItem.Board && itemCandle.Seccode == CandlesItem.Seccode && itemCandle.Period == CandlesItem.Period)
                                        {
                                            foreach (var itemC in itemCandle.Candle)
                                            {
                                                if (itemC.DateTime == candle.DateTime)
                                                {
                                                    addCandle = false;
                                                    itemC.Close = candle.Close;
                                                    itemC.High = candle.High;
                                                    itemC.Low = candle.Low;
                                                    itemC.Open = candle.Open;
                                                    itemC.Volume = candle.Volume;
                                                    itemC.Oi = candle.Oi;
                                                }
                                            }
                                            if (addCandle)
                                                itemCandle.Candle.Add(candle);
                                        }
                                    }

                                }
                            }
                        }
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                        }
                    }
                }
                #endregion

                #region Данные по клиенту client
                if (section == "ticks")
                {
                    if (ename == "tick")
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            TickItem = new Tick();
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                        {
                            AddTick();
                        }
                    }
                    else
                    {
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                            if (ename == TickEnum.seccode.ToString())
                                TickItem.Seccode = evalue;
                            if (ename == TickEnum.board.ToString())
                                TickItem.Board = evalue;
                            if (ename == TickEnum.tradetime.ToString())
                                TickItem.TimeDeal = Convert.ToDateTime(evalue);
                        }
                    }
                }
                #endregion

                #region Получение заявок и стоп-заявок orders

                if (section == "orders")
                {
                    #region Заявки

                    if (ename == "order")
                    {
                        if (xr.Depth == 1)
                            _level1 = ename;
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            OrderItem = new Order();
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                if (i == 0)
                                    OrderItem.Transactionid = Convert.ToInt32(xr.GetAttribute(i));
                            }
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                        {
                            AddOrders();
                        }
                    }
                    if (_level1 == "order")
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                str = str + xr.GetAttribute(i) + ";";
                            }
                        }
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                            if (ename == OrdersEnum.orderno.ToString())
                                OrderItem.Orderno = Convert.ToInt64(evalue);
                            if (ename == OrdersEnum.secid.ToString())
                                OrderItem.Secid = Convert.ToInt32(evalue);
                            if (ename == OrdersEnum.board.ToString())
                                OrderItem.Board = evalue;
                            if (ename == OrdersEnum.seccode.ToString())
                                OrderItem.Seccode = evalue;
                            if (ename == OrdersEnum.client.ToString())
                                OrderItem.Client = evalue;

                            if (ename == OrdersEnum.status.ToString())
                                OrderItem.Status = evalue;
                            if (ename == OrdersEnum.buysell.ToString())
                                OrderItem.Buysell = evalue;
                            if (ename == OrdersEnum.time.ToString())
                                OrderItem.Time = Convert.ToDateTime(evalue);
                            if (ename == OrdersEnum.accepttime.ToString())
                                OrderItem.Accepttime = Convert.ToDateTime(evalue);

                            if (ename == OrdersEnum.brokerref.ToString())
                                OrderItem.Brokerref = evalue;
                            if (ename == OrdersEnum.balance.ToString())
                                OrderItem.Balance = Convert.ToInt32(evalue);
                            if (ename == OrdersEnum.price.ToString())
                                OrderItem.Price = Convert.ToDouble(evalue.Replace('.', ','));

                            if (ename == OrdersEnum.quantity.ToString())
                                OrderItem.Quantity = Convert.ToInt32(evalue);
                            if (ename == OrdersEnum.hidden.ToString())
                                OrderItem.Hidden = Convert.ToInt32(evalue);
                            if (ename == OrdersEnum.withdrawtime.ToString())
                                if (evalue != 0.ToString())
                                    OrderItem.Withdrawtime = Convert.ToDateTime(evalue);

                            if (ename == OrdersEnum.result.ToString())
                                OrderItem.Result = evalue;
                        }
                    }
                    #endregion

                    #region Стоп-заявки

                    if (ename == "stoporder")
                    {
                        if (xr.Depth == 1)
                            _level1 = ename;
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            StopOrderItem = new StopOrder();
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                if (i == 0)
                                    StopOrderItem.Transactionid = Convert.ToInt32(xr.GetAttribute(i));
                            }
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                        {
                            AddStopOrders();
                        }
                    }
                    if (_level1 == "stoporder")
                    {

                        if (xr.Depth == 2)
                            _level2 = ename;

                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                str = str + xr.GetAttribute(i) + ";";
                            }
                        }
                        if (xr.NodeType == XmlNodeType.Text)
                        {

                            if (ename == StopOrdersEnum.activeorderno.ToString())
                                StopOrderItem.Activeorderno = Convert.ToInt64(evalue);
                            if (ename == StopOrdersEnum.secid.ToString())
                                StopOrderItem.Secid = Convert.ToInt32(evalue);
                            if (ename == StopOrdersEnum.board.ToString())
                                StopOrderItem.Board = evalue;
                            if (ename == StopOrdersEnum.seccode.ToString())
                                StopOrderItem.Seccode = evalue;
                            if (ename == StopOrdersEnum.client.ToString())
                                StopOrderItem.Client = evalue;

                            if (ename == StopOrdersEnum.byusell.ToString())
                                StopOrderItem.Buysell = evalue;
                            if (ename == StopOrdersEnum.canceller.ToString())
                                StopOrderItem.Canceller = evalue;
                            if (ename == StopOrdersEnum.alltradeno.ToString())
                                StopOrderItem.Alltradeno = Convert.ToInt64(evalue);
                            if (ename == StopOrdersEnum.validbefore.ToString())
                                StopOrderItem.Validbefore = Convert.ToDateTime(evalue);

                            if (ename == StopOrdersEnum.author.ToString())
                                StopOrderItem.Author = evalue;
                            if (ename == StopOrdersEnum.accepttime.ToString())
                                StopOrderItem.Accepttime = Convert.ToDateTime(evalue);
                            if (ename == StopOrdersEnum.linkedorderno.ToString())
                                StopOrderItem.Linkedorderno = Convert.ToInt64(evalue);

                            if (ename == StopOrdersEnum.expadate.ToString())
                                StopOrderItem.Expdate = Convert.ToDateTime(evalue);
                            if (ename == StopOrdersEnum.status.ToString())
                                StopOrderItem.Status = evalue;

                            if (_level2 == "stoploss")
                            {
                                if (ename == StopOrdersSlEnum.activationprice.ToString())
                                    StopOrderItem.SlActivationPrice = Convert.ToDouble(evalue.Replace('.', ','));
                                if (ename == StopOrdersSlEnum.guardtime.ToString())
                                    StopOrderItem.SlGuardTime = Convert.ToDateTime(evalue);
                                if (ename == StopOrdersSlEnum.brokerref.ToString())
                                    StopOrderItem.SlBrokerref = evalue;

                                if (ename == StopOrdersSlEnum.quantity.ToString())
                                {
                                    try
                                    {
                                        StopOrderItem.SlQuantity = Convert.ToInt32(evalue);
                                    }
                                    catch 
                                    {
                                        StopOrderItem.SlQuantity = 0;
                                    }
                                }

                                if (ename == StopOrdersSlEnum.bymarket.ToString())
                                    StopOrderItem.Slbymarket = evalue;
                                if (ename == StopOrdersSlEnum.orderprice.ToString())
                                    StopOrderItem.SlOrderPrice = Convert.ToDouble(evalue.Replace('.', ','));
                            }

                            if (_level2 == "takeprogit")
                            {
                                if (ename == StopOrdersTpEnum.activationprice.ToString())
                                    StopOrderItem.TpActivationPrice = Convert.ToDouble(evalue.Replace('.', ','));
                                if (ename == StopOrdersTpEnum.guardtime.ToString())
                                    StopOrderItem.TpGuardTime = Convert.ToDateTime(evalue);
                                if (ename == StopOrdersTpEnum.brokerref.ToString())
                                    StopOrderItem.TpBrokerref = evalue;

                                if (ename == StopOrdersTpEnum.quantity.ToString())
                                    StopOrderItem.TpQuantity = Convert.ToInt32(evalue);
                                if (ename == StopOrdersTpEnum.extremum.ToString())
                                    StopOrderItem.TpExtremum = Convert.ToDouble(evalue.Replace('.', ','));
                                if (ename == StopOrdersTpEnum.level.ToString())
                                    StopOrderItem.TpLevel = Convert.ToDouble(evalue.Replace('.', ','));
                                if (ename == StopOrdersTpEnum.correction.ToString())
                                    StopOrderItem.TpCorrection = Convert.ToDouble(evalue.Replace('.', ','));
                                if (ename == StopOrdersTpEnum.guardspread.ToString())
                                    StopOrderItem.TpGuardSpread = Convert.ToDouble(evalue.Replace('.', ','));
                            }
                        }
                    }
                    #endregion
                }
                #endregion

                #region Данные по клиенту trades/ deals
                if (section == "trades")
                {
                    if (ename == "trade")
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            DealItem = new Deal();
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                            AddDeal();
                    }
                    else
                    {
                        line = "";
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                            if (ename == DealsEnum.secid.ToString())
                                DealItem.Secid = Convert.ToInt32(evalue);
                            if (ename == DealsEnum.tradeno.ToString())
                                DealItem.Tradeno = Convert.ToInt64(evalue);
                            if (ename == DealsEnum.orderno.ToString())
                                DealItem.Orderno = Convert.ToInt64(evalue);
                            if (ename == DealsEnum.board.ToString())
                                DealItem.Board = evalue;
                            if (ename == DealsEnum.seccode.ToString())
                                DealItem.Seccode = evalue;
                            if (ename == DealsEnum.client.ToString())
                                DealItem.Client = evalue;
                            if (ename == DealsEnum.buysell.ToString())
                                DealItem.Buysell = evalue;
                            if (ename == DealsEnum.time.ToString())
                                DealItem.Time = Convert.ToDateTime(evalue);
                            if (ename == DealsEnum.brokerref.ToString())
                                DealItem.Brokerref = evalue;
                            if (ename == DealsEnum.value.ToString())
                                DealItem.Value = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == DealsEnum.comission.ToString())
                                DealItem.Comission = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == DealsEnum.price.ToString())
                                DealItem.Price = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == DealsEnum.quantity.ToString())
                                DealItem.Quantity = Convert.ToInt32(evalue);
                            if (ename == DealsEnum.currentpos.ToString())
                                DealItem.Currentpos = Convert.ToInt32(evalue);

                        }
                    }
                }
                #endregion

                #region Обработка на подписанные бумаги quotations
                if (section == "quotations") //обрабатываем заявки
                {
                    if (ename == "quotation" || ename == "sec_position")
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            QuotationsItem = new Quotations();
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                if (i == 0)
                                    QuotationsItem.Secid = Convert.ToInt32(xr.GetAttribute(i));
                            }
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                        {
                            AddQuotations();
                        }
                    }
                    else
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                str = str + xr.GetAttribute(i) + ";";
                            }
                        }
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                            if (ename == QuatationsEnem.board.ToString())
                                QuotationsItem.Board = evalue;
                            if (ename == QuatationsEnem.seccode.ToString())
                                QuotationsItem.Seccode = evalue;
                            if (ename == QuatationsEnem.point_cost.ToString())
                                QuotationsItem.PointCost = Convert.ToDouble(evalue.Replace('.', ',')); ;
                            if (ename == QuatationsEnem.open.ToString())
                                QuotationsItem.Open = Convert.ToDouble(evalue.Replace('.', ',')); ;

                            if (ename == QuatationsEnem.bid.ToString())
                                QuotationsItem.Bid = Convert.ToDouble(evalue.Replace('.', ',')); ;
                            if (ename == QuatationsEnem.offer.ToString())
                                QuotationsItem.Offer = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == QuatationsEnem.last.ToString())
                                QuotationsItem.Last = Convert.ToDouble(evalue.Replace('.', ',')); ;
                            if (ename == QuatationsEnem.change.ToString())
                                QuotationsItem.Change = Convert.ToDouble(evalue.Replace('.', ','));

                            if (ename == QuatationsEnem.closeprice.ToString())
                                QuotationsItem.Closeprice = Convert.ToDouble(evalue.Replace('.', ',')); ;
                            if (ename == QuatationsEnem.status.ToString())
                                QuotationsItem.Status = evalue;
                            if (ename == QuatationsEnem.tradingstatus.ToString())
                                QuotationsItem.Tradingstatus = evalue;
                        }
                    }
                }
                #endregion

                #region Обработка на подписанные бумаги allTrades
                if (section == "alltrades") //обрабатываем сделки
                {
                    if (ename == "trade")
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            AllTradesItem = new AllTrades();
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                if (i == 0)
                                    AllTradesItem.Secid = Convert.ToInt32(xr.GetAttribute(i));
                            }
                        }
                        if (xr.NodeType == XmlNodeType.EndElement)
                        {
                            AddAllTrades();
                        }
                    }
                    else
                    {
                        if (xr.NodeType == XmlNodeType.Element)
                        {
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                str = str + xr.GetAttribute(i) + ";";
                            }
                        }
                        if (xr.NodeType == XmlNodeType.Text)
                        {
                            if (ename == AllTradesEnum.secid.ToString())
                                AllTradesItem.Secid = Convert.ToInt32(evalue);
                            if (ename == AllTradesEnum.seccode.ToString())
                                AllTradesItem.Seccode = evalue;
                            if (ename == AllTradesEnum.tradeno.ToString())
                                AllTradesItem.Tradeno = Convert.ToInt64(evalue); ;
                            if (ename == AllTradesEnum.time.ToString())
                                AllTradesItem.TimeDeal = Convert.ToDateTime(evalue); ;

                            if (ename == AllTradesEnum.baord.ToString())
                                AllTradesItem.Board = evalue;
                            if (ename == AllTradesEnum.price.ToString())
                                AllTradesItem.Price = Convert.ToDouble(evalue.Replace('.', ','));
                            if (ename == AllTradesEnum.buysell.ToString())
                                AllTradesItem.Buysell = evalue; ;
                            if (ename == AllTradesEnum.openinterest.ToString())
                                AllTradesItem.OpenIterest = Convert.ToInt32(evalue);

                            if (ename == AllTradesEnum.period.ToString())
                                AllTradesItem.Period = evalue;
                        }
                    }
                }
                #endregion

                //................................................................................
                if (line.Length > 0)
                {
                    //line = new string(' ',xr.Depth*2) + line;
                    if (info.Length > 0) info = info + (char)13 + (char)10;
                    info = info + line;
                }
            }
            if (info.Length > 0) WriteLog(info);
            // вывод дополнительной информации для удобства отладки
        }

        private void ClearCollection()
        {
            DataProvider.SecuritiesList.Clear();
            DataProvider.DealList.Clear();
            DataProvider.ClietnAccountsList.Clear();
        }

        /// <summary>
        /// Добавление данных по бамаге в коллекция
        /// </summary>
        public void AddSecurities()
        {
            DataProvider.SecuritiesList.Add(SecuritiesItem);
        }

        /// <summary>
        /// Добавление клиентских счетов в коллекцию
        /// </summary>
        public void AddClientAccount()
        {

            DataProvider.ClietnAccountsList.Add(ClientAccountItem);
        }

        /// <summary>
        /// Добавление новой сделки
        /// </summary>
        public void AddDeal()
        {
            DataProvider.DealList.Add(DealItem);
        }

        /// <summary>
        /// Обновление подписки на инструменты (таблица текущих параметров)
        /// </summary>
        public void AddQuotations()
        {
            bool addNewInstrument = true;

            if (DataProvider.QuotationsList.Count > 0)
                foreach (var item in DataProvider.QuotationsList)
                {
                    if (item.Board == QuotationsItem.Board && item.Seccode == QuotationsItem.Seccode)
                    {
                        const double tolerance = 0;
                        if (Math.Abs(QuotationsItem.Bid) > tolerance)
                            item.Bid = QuotationsItem.Bid;
                        if (Math.Abs(QuotationsItem.Offer) > tolerance)
                            item.Offer = QuotationsItem.Offer;
                        if (QuotationsItem.Last != 0)
                            item.Last = QuotationsItem.Last;
                        if (QuotationsItem.Change != 0)
                            item.Change = QuotationsItem.Change;
                        item.Status = QuotationsItem.Status;
                        item.Tradingstatus = QuotationsItem.Tradingstatus;
                        addNewInstrument = false;
                    }
                }
            if (addNewInstrument)
                DataProvider.QuotationsList.Add(QuotationsItem);
        }

        /// <summary>
        /// Изменение параметров последней сделки, главное времени
        /// </summary>
        public void AddAllTrades()
        {
            bool addNewInstrument = true;

            if (DataProvider.AllTrade.Count > 0)
                foreach (var item in DataProvider.AllTrade)
                {
                    if (AllTradesItem.Period == "N")
                        if (item.Secid == AllTradesItem.Secid && item.Seccode == AllTradesItem.Seccode)
                        {
                            item.Tradeno = AllTradesItem.Tradeno;
                            item.TimeDeal = AllTradesItem.TimeDeal;
                            item.Price = AllTradesItem.Price;
                            item.Quantity = AllTradesItem.Quantity;
                            item.Buysell = AllTradesItem.Buysell;
                            addNewInstrument = false;
                        }
                        else
                        {
                            addNewInstrument = false;
                        }
                }
            if (addNewInstrument)
                DataProvider.AllTrade.Add(AllTradesItem);
        }
        /// <summary>
        /// Добавление или изменение текущих параметров заявки
        /// </summary>
        private void AddOrders()
        {
            bool addNewOrder = true;

            if (DataProvider.OrderList.Count > 0)
            {
                foreach (var item in DataProvider.OrderList)
                {
                    if ((item.Transactionid == OrderItem.Transactionid) || (item.Orderno == OrderItem.Orderno && OrderItem.Orderno != 0))
                    {
                        if (OrderItem.Orderno != 0)
                            item.Orderno = OrderItem.Orderno;
                        if (OrderItem.Status != item.Status && !String.IsNullOrEmpty(OrderItem.Status))
                            item.Status = OrderItem.Status;
                        if (OrderItem.Accepttime >= item.Accepttime)
                            item.Accepttime = OrderItem.Accepttime;
                        if (OrderItem.Balance != item.Balance)
                            item.Balance = OrderItem.Balance;
                        if (!String.IsNullOrEmpty(OrderItem.Result))
                            item.Result = OrderItem.Result;
                        addNewOrder = false;
                    }
                }
            }

            if (addNewOrder)
                DataProvider.OrderList.Add(OrderItem);
        }

        /// <summary>
        /// Добавление стоп-заявок
        /// </summary>
        private void AddStopOrders()
        {
            bool addNewStopOrder = true;

            if (DataProvider.StopOrderList.Count > 0)
            {
                foreach (var item in DataProvider.StopOrderList)
                {
                    if ((item.Transactionid == StopOrderItem.Transactionid))
                    {
                        if (StopOrderItem.Activeorderno != 0)
                            item.Activeorderno = StopOrderItem.Activeorderno;
                        if (StopOrderItem.Canceller != item.Canceller && !String.IsNullOrEmpty(StopOrderItem.Canceller))
                            item.Canceller = StopOrderItem.Canceller;
                        if (StopOrderItem.Accepttime >= item.Accepttime)
                            item.Accepttime = StopOrderItem.Accepttime;
                        if (StopOrderItem.Alltradeno != 0)
                            item.Alltradeno = StopOrderItem.Alltradeno;
                        if (StopOrderItem.Linkedorderno != 0)
                            item.Linkedorderno = StopOrderItem.Linkedorderno;
                        if (!String.IsNullOrEmpty(StopOrderItem.Status))
                            item.Status = StopOrderItem.Status;
                        if (StopOrderItem.TpExtremum != 0)
                            item.TpExtremum = StopOrderItem.TpExtremum;
                        addNewStopOrder = false;
                    }
                }
            }

            if (addNewStopOrder)
                DataProvider.StopOrderList.Add(StopOrderItem);
        }

        /// <summary>
        /// Добавление или изменение данных по денежным позиция на ММВБ
        /// </summary>
        private void AddMoneyPosition()
        {
            bool addNewMoneyPosition = true;

            if (DataProvider.MoneyPositionList.Count > 0)
            {
                foreach (var item in DataProvider.MoneyPositionList)
                {
                    if ((item.Client == MoneyPositionItem.Client) && (item.Register == MoneyPositionItem.Register && item.Asset == MoneyPositionItem.Asset))
                    {
                        if (item.Saldo != MoneyPositionItem.Saldo && MoneyPositionItem.Saldo != 0)
                            item.Saldo = MoneyPositionItem.Saldo;
                        if (item.Saldoin != MoneyPositionItem.Saldoin && MoneyPositionItem.Saldoin != 0)
                            item.Saldoin = MoneyPositionItem.Saldoin;
                        if (item.Bought != MoneyPositionItem.Bought && MoneyPositionItem.Bought != 0)
                            item.Bought = MoneyPositionItem.Bought;
                        if (item.Sold != MoneyPositionItem.Sold && MoneyPositionItem.Sold != 0)
                            item.Sold = MoneyPositionItem.Sold;
                        if (item.Ordbuy != MoneyPositionItem.Ordbuy && MoneyPositionItem.Ordbuy != 0)
                            item.Ordbuy = MoneyPositionItem.Ordbuy;
                        if (item.Ordbuycond != MoneyPositionItem.Ordbuycond && MoneyPositionItem.Ordbuycond != 0)
                            item.Ordbuycond = MoneyPositionItem.Ordbuycond;
                        if (item.Comission != MoneyPositionItem.Comission && MoneyPositionItem.Comission != 0)
                            item.Comission = MoneyPositionItem.Comission;
                        addNewMoneyPosition = false;
                    }
                }
            }
            if (addNewMoneyPosition)
                DataProvider.MoneyPositionList.Add(MoneyPositionItem);
        }

        /// <summary>
        /// Добавление и изменение поизций на ММВБ
        /// </summary>
        private void AddSecPosition()
        {
            bool addNewSecPosition = true;

            if (DataProvider.SecPositionList.Count > 0)
            {
                foreach (var item in DataProvider.SecPositionList)
                {
                    if ((item.Client == SecPositionItem.Client) && (item.Seccode == SecPositionItem.Seccode && item.Market == SecPositionItem.Market && item.Register == SecPositionItem.Register))
                    {
                        if (item.Bought != SecPositionItem.Bought && SecPositionItem.Bought != 0)
                            item.Bought = SecPositionItem.Bought;
                        if (item.Sold != SecPositionItem.Sold && SecPositionItem.Sold != 0)
                            item.Sold = SecPositionItem.Sold;
                        if (item.Saldo != SecPositionItem.Saldo && SecPositionItem.Saldo != 0)
                            item.Saldo = SecPositionItem.Saldo;
                        if (item.Ordbuy != SecPositionItem.Ordbuy && SecPositionItem.Ordbuy != 0)
                            item.Ordbuy = SecPositionItem.Ordbuy;
                        if (item.Ordsell != SecPositionItem.Ordsell && SecPositionItem.Ordsell != 0)
                            item.Ordsell = SecPositionItem.Ordsell;
                        if (item.Saldo != SecPositionItem.Saldo && SecPositionItem.Saldo != 0)
                            item.Saldo = SecPositionItem.Saldo;
                        addNewSecPosition = false;
                    }
                }
            }
            if (addNewSecPosition)
                DataProvider.SecPositionList.Add(SecPositionItem);
        }

        private void AddTick()
        {
            foreach (var item in DataProvider.GechikRobotItemList)
            {
                if (item.Instrument == TickItem.Seccode)
                {
                    //Обновляем данные по свечкам, если изменение приозошло хоть на минуту
                    //if (TickItem.TimeDeal.TimeOfDay.Minutes != item.PrevTime.Minutes || TickItem.TimeDeal.TimeOfDay.Hours != item.PrevTime.Hours)
                    //{
                    //    if (DataProvider.SecuritiesList.Count > 0)
                    //        foreach (var item2 in DataProvider.SecuritiesList)
                    //        {
                    //            if (item2.Seccode == item.Instrument)
                    //            {
                    //                if (!TicksListInstruments.Contains(item2.Secid))
                    //                {
                    //                    TicksListInstruments.Add(item2.Secid);
                    //                    string result = OConn.SendCommand(DataProvider.TransaqCommand.SubscribeTick(TicksListInstruments));
                    //                    WriteLog("ServerReply: " + result);
                    //                }

                    //                WriteLog("ServerReply: " + res);
                    //            }
                    //        }
                    //}

                    if (item.PrevTime.Minutes != TickItem.TimeDeal.TimeOfDay.Minutes)
                    {
                        try
                        {
                            int secID = 0;
                            if (DataProvider.SecuritiesList.Count > 0)
                                foreach (var item2 in DataProvider.SecuritiesList)
                                {
                                    if (item2.Seccode == item.Instrument)
                                    {
                                        secID = item2.Secid;
                                    }
                                }

                            string res = OConn.SendCommand(
                                DataProvider.TransaqCommand.GetHistoryDate(
                                    secID,
                                    DictionaryTimeFrame.FirstOrDefault(x => x.Value == item.TimeFrame).Key,
                                    2, "true"));

                        }
                        catch
                        {
                        }


                    }
                    item.PrevTime = TickItem.TimeDeal.TimeOfDay;
                }
            }
        }

        enum SecuritiesEnum
        {
            security,


            seccode,
            board,
            market,
            shortname,
            decimals,
            minstep,
            lotsize,
            pointCost,
            opmask,

            usercredit,
            bymarket,
            nosplit,
            immorcancel,
            cancelbalance,

            sectype
        }

        private enum ClietnAccountEnum
        {
            id,
            type,
            currency,
            ml_intraday,
            ml_overnight,
            ml_restrict,
            ml_call,
            ml_close
        }

        private enum QuatationsEnem
        {
            secid,
            board,
            seccode,
            point_cost,
            open,
            bid,
            offer,
            last,
            change,
            closeprice,
            status,
            tradingstatus

        }

        private enum MoneyPositionEnum
        {
            client,
            market,
            register,
            asset,
            shortname,
            saldoin,
            bought,
            sold,
            saldo,
            ordbuy,
            ordbuycond,
            comission

        }

        private enum SecPositionEnum
        {
            secid,
            market,
            seccode,
            register,
            client,
            shortname,
            saldoin,
            saldomin,
            bought,
            sold,
            saldo,
            ordbuy,
            ordsell

        }

        private enum OrdersEnum
        {
            transactionid,
            orderno,
            secid,
            board,
            seccode,
            client,
            status,
            buysell,
            time,
            accepttime,
            brokerref,
            balance,
            price,
            quantity,
            hidden,
            withdrawtime,
            result

        }

        private enum StopOrdersEnum
        {
            transactionid,
            activeorderno,
            secid,
            board,
            seccode,
            client,
            byusell,
            canceller,
            alltradeno,
            validbefore,
            author,
            accepttime,
            linkedorderno,
            expadate,
            status
        }

        private enum StopOrdersSlEnum
        {
            usecredit,
            activationprice,
            guardtime,
            brokerref,
            quantity,
            bymarket,
            orderprice
        }

        private enum StopOrdersTpEnum
        {
            activationprice,
            guardtime,
            brokerref,
            quantity,
            extremum,
            level,
            correction,
            guardspread
        }

        private enum DealsEnum
        {
            secid,
            tradeno,
            orderno,
            board,
            seccode,
            client,
            buysell,
            time,
            brokerref,
            value,
            comission,
            price,
            quantity,
            currentpos

        }

        private enum TickEnum
        {
            secid,
            tradeno,
            tradetime,
            price,
            quantity,
            preiod,
            buysell,
            openinterest,
            board,
            seccode

        }

        private enum AllTradesEnum
        {
            secid,
            seccode,
            tradeno,
            time,
            baord,
            price,
            quantity,
            buysell,
            openinterest,
            period
        }
    }
}
